package org.come.control;

import com.tool.ModerateTask.Hero;
import com.tool.image.ImageMixDeal;
import com.tool.image.ManimgAttribute;
import com.tool.pet.PetProperty;
import com.tool.role.RoleData;
import com.tool.role.RoleLingFa;
import com.tool.role.RoleProperty;
import com.tool.role.RoleTX;
import com.tool.time.TimeLimit;
import org.come.Frame.BoothBoxJframe;
import org.come.Frame.WelcomeXyJframe;
import org.come.Jpanel.WelcomeXyJpanel;
import org.come.Jpanel.ZhuJpanel;
import org.come.action.FromServerAction;
import org.come.action.MapAction;
import org.come.bean.*;
import org.come.entity.Mount;
import org.come.entity.RoleSummoning;
import org.come.socket.DownLoadTxt;
import org.come.socket.GameClient;
import org.come.socket.SendMessageUntil;
import org.come.test.Main;
import org.come.thread.AutoTaskTimeControlRunnable;
import org.come.thread.LoadYeguaiRunnable;
import org.come.thread.TimeControlRunnable;
import org.come.thread.TimeControlRunnableNew;
import org.come.until.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EnterGameControl implements FromServerAction {
	private TimeControlRunnable controlRunnable;

	private TimeControlRunnableNew controlRunnableNew;
	private AutoTaskTimeControlRunnable autotaskcontrolRunnable;

	// 添加一个线程池用于执行后台任务，避免频繁创建线程
	private static final ExecutorService BACKGROUND_EXECUTOR = Executors.newCachedThreadPool();

	@Override
	public void controlMessFromServer(String mes, String type) {
		// TODO Auto-generated method stub
		enterGameBean list2 = GsonUtil.getGsonUtil().getgson().fromJson(mes, enterGameBean.class);
		LoginResult role = list2.getLoginResult();
		RoleAttribute roleAttribute = list2.getRoleAttribute();
		RoleData.getRoleData().setLoginResult(role);
		RoleData.getRoleData().setRoleAttribute(roleAttribute);
		System.out.println((Object) ("Rolename" + "=" + role.getRolename() + "=" + role.getSpecies_id() + "=" + Main.index) + "=" + role.getRace_name() + "=" + role.getRole_id() + "=" + GameClient.BT);
		try {
			if (GameClient.DXCL == null) {
				ImageMixDeal.userimg = new ManimgAttribute(new RoleShow(role), 0);
				Util.loadMap(role.getMapid().intValue(), role.getX().intValue(), role.getY().intValue());
				GameClient.DXCL = role.getRole_id().toString() + "|" + GameClient.username + "|" + GameClient.userpasw;
				RoleTX.getRoleTX().initRole(role.getSpecies_id());
				ControlNpcXmlUntil.GetXmlPath("npcMenu.xml");
				new TestMain();

				// 常用角色-更新角色信息
				LoginRoleInfo roleInfo = Main.frame.getRoleInfo();
				roleInfo.setRoleId(role.getRole_id());
				roleInfo.setRoleName(role.getRolename());
				roleInfo.setRoleLvl(role.getGrade());
				roleInfo.setRaceId(role.getSpecies_id());
				roleInfo.setRaceName(role.getRace_name());
				roleInfo.setRoleIp(DownLoadTxt.ip);
				roleInfo.setRolePort(DownLoadTxt.port);
				Main.frame.getLoginInfo().updateLoginRole(roleInfo);

				// 将创建角色窗体关闭
				Main.frame.dispose();
				Main.frame = null;
//				com.main.Main.frame.dispose();
//				com.main.Main.frame = null;
//			}else{
//				if(FightingMixDeal.State != HandleState.USUAL) {
//					Map<Integer, ActivityModelJpanel> mapActivityModelPanel = null;
//					ActivityModelJpanel activityModelJpanel = null;
//					try {
//						mapActivityModelPanel = ActivityJframe.getActivityJframe().getActivityJpanel().getMapActivityModelPanel();
//						activityModelJpanel = mapActivityModelPanel.get(scriptTask.getTaskSetID());
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//					if (activityModelJpanel != null) {
//						String guide = activityModelJpanel.getActiveBase().getGuide();
//						String[] v = guide.split("-");
//						if (v.length == 5) {
//							TimeControlRunnable.addTask(new ScriptTask(v, activityModelJpanel.getActiveBase().getSid()));
//						}
//					}
//				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		Util.uptime(role.getUptime());
		if (role != null) {
			if (ImageMixDeal.userimg == null) {
				ImageMixDeal.userimg = new ManimgAttribute(new RoleShow(role), 0);
				ImageMixDeal.username = role.getRolename();
			} else {
				ImageMixDeal.userimg.getRoleShow().init(role);
				ImageMixDeal.username = role.getRolename();
				ImageMixDeal.userimg.changeskin(null);
				ImageMixDeal.userimg.setAppellation(role.getTitle());
				ImageMixDeal.userimg.initTeam();

				// 定期清理缓存，避免内存占用过高
				org.come.until.UserMessUntil.checkAndClearCache();
			}
			Util.dogame(role);

			// 使用同步块确保线程安全
			synchronized (this) {
				if (controlRunnable == null) {
					controlRunnable = new TimeControlRunnable();
					Thread t2 = new Thread(controlRunnable);
					t2.start();

//					controlRunnableNew = new TimeControlRunnableNew();
//					Thread t23 = new Thread(controlRunnableNew);
//					t23.start();

				}
				if (autotaskcontrolRunnable == null) {
					autotaskcontrolRunnable = new AutoTaskTimeControlRunnable();
					Thread t2 = new Thread(autotaskcontrolRunnable);
					t2.start();

				}
			}
		}
		boolean is=false;
		// 物品初始化
		if (list2.getList() != null) {
			GoodsListFromServerUntil.Classification(list2.getList(), list2.getPackRecord().getRecord());
			is=true;
		}
		// 玩家数据初始化
		RoleData roleData = RoleData.getRoleData();
		//system.out.println("Rolename:"+ roleData.getLoginResult().getRolename() + " id：" + roleData.getLoginResult().getRole_id() + "&id:" + roleData.getLoginResult().getSpecies_id());


		roleData.init(list2.getPackRecord(), list2.getRoleSystem(), list2.getPrivateData(),role);
		Hero.getHero();
		if (is) {
			TimeLimit.getLimits();
			RoleProperty.getRoleProperty();
		}
		if (ImageMixDeal.userimg == null) {
			return;
		}
		role = roleData.getLoginResult();
		if (list2.getStall() != null) {
			BoothBoxJframe.getBoothboxjframe().getBoothboxjpanel().init(list2.getStall());
		}
		if (list2.getStallBeans() != null) {
			for (int i = list2.getStallBeans().size() - 1; i >= 0; i--) {
				ImageMixDeal.stall(list2.getStallBeans().get(i));
			}
		}
		// 玩家灵宝初始化
		if (list2.getLingbaos() != null) {
			RoleLingFa.getRoleLingFa().lingChange(list2.getLingbaos());
			RoleProperty.ResetEw();
		}
		// 进行收到的消息处理
		if (list2.getRoleShows().size() != 0) {
			for (int i = list2.getRoleShows().size() - 1; i >= 0; i--) {
				RoleShow roleShow = list2.getRoleShows().get(i);
				if (roleShow == null) {
					continue;
				}
				ManimgAttribute attribute = ImageMixDeal.huoquLogin(roleShow.getRolename());
				if (attribute == null) {
					ImageMixDeal.Playerimgmap.put(roleShow.getRolename(), new ManimgAttribute(roleShow, 1));
				}else{
					attribute.setRoleShow(roleShow);
					attribute.changeskin(null);
					attribute.CZmove();
				}
			}
		}
		// 接收野怪集合 使用线程池执行后台任务
		if (list2.getMonster() != null) {
			BACKGROUND_EXECUTOR.execute(new LoadYeguaiRunnable(list2.getMonster()));
		}
		// 判断宠物列表里面的信息是否为空，有的画则放入到静态中备用
		if (list2.getRoleSummonings() != null) {
			UserMessUntil.setPetListTable(PetControl.qc(list2.getRoleSummonings()));
			UserMessUntil.setChosePetMes(null);
			BigDecimal id = role.getSummoning_id();
			// 有携带，那么将该宠物信息保存到已经选中的类中
			for (int i = 0; i < UserMessUntil.getPetListTable().size(); i++) {
				RoleSummoning pet = UserMessUntil.getPetListTable().get(i);
				if (pet.getBasishp() == 0) {
					int[] petvalue = PetProperty.getPetHMASp(pet);
					pet.setBasishp(petvalue[0]);
					pet.setBasismp(petvalue[1]);
				}
				if (id != null && pet.getSid().compareTo(id) == 0) { // 设置保存
					RoleSummoning petE = UserMessUntil.getPetListTable().get(i);
					UserMessUntil.setChosePetMes(petE);
					Article.souxie(petE);// 初始化角色携带的召唤兽信息
					String path = "img/newHead/p" + petE.getSummoningskin() + ".png";
					ZhuJpanel.setLabpetimg(path);

				}
			}

		}
		//召唤兽寄存
		if (list2.getRoleDepositSummonings() != null) {
			UserMessUntil.setDepositPetListTable(list2.getRoleDepositSummonings());
		}
		// 玩家坐骑初始化
		if (list2.getMounts() != null) {
			if (list2.getMounts().size() != 0) {
				// 使用局部变量减少对ZhuJpanel.getListMount()的重复调用
				java.util.List<Mount> mountList = ZhuJpanel.getListMount();
				for (int i = 0; i < list2.getMounts().size(); i++) {
					mountList.add(i, list2.getMounts().get(i));
					if(role.getMount_id()!=null && role.getMount_id()>0) {
						if(role.getMount_id().equals(list2.getMounts().get(i).getMountid())) {
							Util.moveGrade = list2.getMounts().get(i).getMoveGrade();
						}
					}
				}
			}
		}
		// 玩家宝宝初始化
		BabyControl.babyinit(list2.getBabys());
		// 玩家伙伴初始化
		roleData.setPals(list2.getPals());

		ImageMixDeal.upScene(list2.getSceneMsg());
		/** zrikka 2020 0414 */
//		SendMessageUntil.CanDoConnectOrNo = true;
		MapAction.flagAction.put(SendMessageUntil.gameServerKey, true);

		// 清理过期缓存
		org.come.until.UserMessUntil.checkAndClearCache();
		/*****/

//		FormsManagement.showForm(104);
//		Hero.getHero().addTask("1004=2=T1486787655=P2_M1230-2180-1880_D300052-万年熊王=P2_M1230-1680-2080_D300053-蓝色妖王=P2_M1230-2260-2380_D300054-黑山妖王=P2_M1230-2760-2120_D300055-三头魔王");
//		Hero.getHero().addTask("1000=2=T1486787655=P2_M1230-2180-1880_D300052-万年熊王=P2_M1230-1680-2080_D300053-蓝色妖王=P2_M1230-2260-2380_D300054-黑山妖王=P2_M1230-2760-2120_D300055-三头魔王");
//		for (int i = 0; i <=104; i++) {
//			try {
//				FormsManagement.showForm(i);
//			} catch (Exception e) {
//				// TODO: handle exception
//			    //system.out.println(i);
//			}
//		}
//		ZhuJpanel.setListFly(list2.getFlys());
		roleData.changeSkin(true);//初始化新人物角色装备武器
		if(role.getGrade()<50) {
			FormsManagement.showForm(3081);
			WelcomeXyJpanel.X = 217;
			WelcomeXyJpanel.updateOX();
		}else {
			LocalDate currentDate = LocalDate.now();
			String dayOfWeek = currentDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA);
			String masg = "";
			if(dayOfWeek.equals("星期一")){
				WelcomeXyJpanel.taskID = 120;
				masg="#Y今天是#G星期一#Y，今日周任务是#R【天降灵猴】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}else if(dayOfWeek.equals("星期二")){
				WelcomeXyJpanel.taskID = 121;
				masg="#Y今天是#G星期二#Y，今日周任务是#R【劫镖任务】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}else if(dayOfWeek.equals("星期三")){
				WelcomeXyJpanel.taskID = 122;
				masg="#Y今天是#G星期三#Y，今日周任务是#R【围剿倭寇】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}else if(dayOfWeek.equals("星期四")){
				WelcomeXyJpanel.taskID = 123;
				masg="#Y今天是#G星期四#Y，今日周任务是#R【城东魅影】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}else if(dayOfWeek.equals("星期五")){
				WelcomeXyJpanel.taskID = 124;
				masg="#Y今天是#G星期五#Y，今日周任务是#R【修罗乱世】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}else if(dayOfWeek.equals("星期六")){
				WelcomeXyJpanel.taskID = 125;
				masg="#Y今天是#G星期六#Y，今日周任务是#R【天元盛世】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}else if(dayOfWeek.equals("星期日")){
				WelcomeXyJpanel.taskID = 126;
				masg="#Y今天是#G星期日#Y，今日周任务是#R【驱逐年兽】#Y请前往#G长安城(264,148)#Y找NPC#R【限时任务】#Y领取，奖励丰厚记得参加哦！#38";
			}
			FormsManagement.showForm(3081);
			WelcomeXyJpanel.MsgList.add(masg);
			WelcomeXyJpanel.taskmsg = "1207-5290-3690-400259";
			WelcomeXyJpanel.indexs = WelcomeXyJpanel.MsgList.size()-1;
			WelcomeXyJpanel.X = 217;
			WelcomeXyJpanel.updateOX();
			WelcomeXyJframe.getWelcomeXyJpanel().getStartbel().setText("前往");
		}
	}
}
